import { ElMessage } from 'element-plus'
import { onMounted, reactive, toRefs } from 'vue'

export const useTable = (requestApi: (params: any) => Promise<any>, initParams: object = {}) => {
	// 表格状态数据
	const state = reactive({
		// 表格数据
		tableData: [],
		// 表格加载状态
		loading: false,
		// 分页数据
		pageable: {
			pageNumber: 1,
			pageSize: 10,
			total: 0
		}
	})

	// * 获取表格数据
	const getTableData = async () => {
		try {
			state.loading = true
			// 合并所有参数【初始化参数(固定参数), 分页参数】
			const totalParam = { ...initParams, ...state.pageable }
			const { data } = await requestApi(totalParam)
			state.loading = false
			state.tableData = data.list
			state.pageable.pageNumber = data.currPage
			state.pageable.pageSize = data.pageSize
			state.pageable.total = data.totalCount
		} catch (error) {
			state.loading = false
			ElMessage.error('接口异常, 未知错误')
			console.error(error)
		}
	}

	// * 生命周期中 调用获取表格数据
	onMounted(() => {
		getTableData()
	})

	// * 页码改变
	const pageChange = (page: number) => {
		state.pageable.pageNumber = page
		getTableData()
	}

	// * 每页条数改变
	const sizeChange = (size: number) => {
		state.pageable.pageNumber = 1
		state.pageable.pageSize = size
		getTableData()
	}

	return {
		...toRefs(state),
		getTableData,
		pageChange,
		sizeChange
	}
}
